package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.GraduateProjectCategory;
import cn.edu.sdjzu.xg.bysj.domain.GraduateProjectSource;
import cn.edu.sdjzu.xg.bysj.domain.GraduateProjectTrueness;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectCategoryService;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectSourceService;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectTruenessService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/graduateProjectSource.ctl")
public class GraduateProjectSourceController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //读取参数id
        String id_str = request.getParameter("id");

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            //如果id = null, 表示响应所有学院对象，否则响应id指定的对象
            if (id_str == null) {
                responses(response);
            } else {
                int id = Integer.parseInt(id_str);
                response(id, response);
            }
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(message);
        }catch(Exception e){
            message.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(message);
        }
    }
    //响应一个对象
    private void response(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找
        GraduateProjectSource graduateProjectSource = GraduateProjectSourceService.getInstance().find(id);
        String graduateProjectType_json = JSON.toJSONString(graduateProjectSource);

        //响应到前端
        response.getWriter().println(graduateProjectType_json);
    }
    //响应所有对象
    private void responses(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //获得所有
        Collection<GraduateProjectSource> graduateProjectSources = GraduateProjectSourceService.getInstance().findAll(null,null);
        String graduateProjectTypes_json = JSON.toJSONString(graduateProjectSources , SerializerFeature.DisableCircularReferenceDetect);

        //响应schools_json到前端
        response.getWriter().println(graduateProjectTypes_json);
    }

}